package org.example.est.service.impl;

import cn.hutool.core.util.StrUtil;
import org.example.est.dao.UsersDao;
import org.example.est.dto.TokenDTO;
import org.example.est.dto.UsersInfoDTO;
import org.example.est.entity.Users;
import org.example.est.common.exception.BusinessException;
import org.example.est.constants.Constants;
import org.example.est.constants.ResultEnum;
import org.example.est.param.SmsLoginParam;
import org.example.est.service.SmsVerifyCodeService;
import org.example.est.service.TokenService;
import org.example.est.service.UsersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;

@Service
public class UserServiceImpl implements UsersService {
    @Autowired
    private UsersDao usersDao;
    @Autowired
    private SmsVerifyCodeService verifyCodeService;
    @Autowired
    private TokenService tokenService;

    @Override
    public Users findById(Long id) {
        return usersDao.selectByPrimaryKey(id);
    }

    @Override
    public Users findByOpenId(String openid){
        return usersDao.findByOpenId(openid);
    }

    @Override
    public Users registe(Users users) {
        usersDao.insertSelective(users);
        return users;
    }

    @Override
    public TokenDTO smsLogin(SmsLoginParam loginParam) {
        //根据手机号获取缓存的验证码
        String phone = loginParam.getPhone();
        String verifyCode = verifyCodeService.getVerifyCode(phone);
        //对比验证码是否正确
        //如果不正确，抛出异常
        if(!StrUtil.equals(verifyCode,loginParam.getSms())){
            throw new BusinessException(ResultEnum.FAIL_VERIFY);
        }
        //如果验证码正确清除验证码
        verifyCodeService.removeVerifyCode(phone);
        //根据手机号查询用户信息
        Users users = usersDao.findByAccount(phone);
        //如果用户信息不存在则进行自动注册
        if (ObjectUtils.isEmpty(users)){
            users = regisgterByPhone(phone);
        }
        //自动登录操作
        TokenDTO tokenDTO = tokenService.generateToken(users);
        tokenService.saveToken(tokenDTO.getToken(),users);
        return tokenDTO;
    }

    @Override
    public UsersInfoDTO getUserInfoByToken(String token){
        Users users = tokenService.getUserInfoByToken(token);
        UsersInfoDTO infoDTO = new UsersInfoDTO();
        BeanUtils.copyProperties(users,infoDTO);
        return infoDTO;
    }

    @Override
    public void logout(String token) {
        tokenService.removeToken(token);
    }


    private Users regisgterByPhone(String phone){
        Users users = new Users();
        users.setAccount(phone);
        users.setUsername(phone);
        users.setIsauthentication(Constants.EST_NOT);
        users.setCreatedtime(new Date());
        users.setIsdelete(Constants.EST_NOT);

        usersDao.insert(users);
        return users;
    }


}
